package com.ordering.login.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ordering.database.ConnectionManager;
import com.ordering.entity.UserInfo;
import com.ordering.util.HibernateUtil;

public class LoginDao{
    private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    /*
    public UserInfo findUser(String username, String password){
        if(username == null || password == null)
            return null;
        ConnectionManager cm = ConnectionManager.getInstance();
        Connection conn = cm.getConnection();
        String sql = "select * from USER_INFO " + "where USERNAME=? and PASSWORD=?";
        try {
            PreparedStatement ps =conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                UserInfo user = createUser(rs);
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private UserInfo createUser(ResultSet rs) throws SQLException {
        UserInfo user = new UserInfo();
        user.setUsername(rs.getString("USERNAME"));
        user.setPassword(rs.getString("PASSWORD"));
        return user;
    }
    
    */
    
    
    
    public UserInfo findUser(String username, String password){
        Session s=null;
        try{
            s=HibernateUtil.getSession();
           
           //from后面是对象，不是表名
            String hql="from UserInfo as user where user.username=:username";//使用命名参数，推荐使用，易读。
            Query query=s.createQuery(hql);
            query.setString("username", username);
           
            List<UserInfo> users =query.list();
            if(users==null||users.size()==0){
                return null;
            }
            for(UserInfo user:users){
                return user;
            }
        }finally{
            if(s!=null)
                s.close();
        }
        return null;
    }
    
    
    public static void main(String[] args) {
        LoginDao dao = new LoginDao();
        UserInfo user = dao.findUser("root", "eyecandy");
        System.out.println(user.getUsername());
    }
}
